package com.iwhalecloud.bss.kite.cucc.service.order;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.hsf.baseinf.service.InfExchangeService;
import com.iwhalecloud.bss.kite.common.callclient.service.IOrderQueryService;
import com.iwhalecloud.bss.kite.common.entity.InfService;
import com.iwhalecloud.bss.kite.common.util.JsonUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.common.validate.annotation.KiteNotBlank;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.api.order.IContractService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ContractDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ContractRequestDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.ContractSimpleDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.DownloadIncludeDataDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttachmentDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.webService.CustContractRsp;
import com.iwhalecloud.bss.kite.cucc.common.callclient.HttpsCallClient;
import com.iwhalecloud.bss.kite.cucc.common.callclient.constant.CallClientEnum;
import com.iwhalecloud.bss.kite.cucc.common.callclient.service.ICuccQueryInfService;
import com.iwhalecloud.bss.kite.cucc.common.util.WebServiceUtil;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceBus;
import com.iwhalecloud.bss.kite.cucc.service.inf.InfServiceHelper;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.IKitePosServiceHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl.KitePosServiceHandler;
import com.iwhalecloud.bss.kite.cucc.service.util.LocalTokenUtil;
import com.iwhalecloud.bss.kite.cucc.service.util.webService.WebServiceHelper;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

import com.ztesoft.zsmart.core.log.ZSmartLogger;
import org.apache.axis.message.SOAPEnvelope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ContractService implements IContractService {

    @Autowired
    IInfServiceBus infServiceBus;
    private static final ZSmartLogger LOGGER = ZSmartLogger.getLogger(ContractService.class);

    /**
     * 查询合同列表
     */
    @Override
    public PageInfo<ContractDTO> queryContractByCustId(String custId, String contractNo, String contractName,
                                                       int pageNum, int pageSize) {
        PageInfo<ContractDTO> pageInfo = new PageInfo<ContractDTO>();
        Map<String, String> param = new HashMap<>();
        param.put("custId", custId);
        param.put("contractNo", contractNo);
        param.put("contractName", contractName);
        param.put("pageNum", pageNum + "");
        param.put("pageSize", pageSize + "");
        String rsp = HttpsCallClient.postString(CallClientEnum.QRY_CUSTOMER_ACCTLIST, param);
        pageInfo = JsonUtils.parseObject(rsp, pageInfo.getClass());
        return pageInfo;
    }

    @Override
    public ContractSimpleDTO createAndUploadContract(ContractRequestDTO contractRequestDTO) {
//        Map<String, String> param = KiteMapUtils.beanToMap(contractRequestDTO);
//        String rsp = HttpsCallClient.postString(CallClientEnum.UPLOAD_CONTRACT, param);
//        Map<String, String> resultMap = JSON.parseObject(rsp, Map.class);
//        if (!"200".equals(KiteMapUtils.getString(resultMap, "code"))) {
//        	ErrorConsts.INF_INVOKE_ERROR.throwOut(KiteMapUtils.getString(resultMap, "message"));
//        }
//        ContractSimpleDTO dto = JsonUtils.parseObject(KiteMapUtils.getString(resultMap, "data"), ContractSimpleDTO.class);

        String code= DcPublicCache.getPCode("20211224001","ZWY");
        if(KiteStringUtils.isNotEmpty(contractRequestDTO.getCataId())&&KiteStringUtils.contains(code,contractRequestDTO.getCataId())){
            IOrderQueryService orderQueryService = SpringUtil.getBean(IOrderQueryService.class);
            InfService infService = orderQueryService.queryServiceBySvcCode(CallClientEnum.UPLOAD_CONTRACT.getServiceCode(), CallClientEnum.UPLOAD_CONTRACT.getCenterCode());

            LoginInfo loginInfo = ContextUtil.getLoginInfo();
            contractRequestDTO.setProvinceCode(loginInfo.getUserInfo().getPostProvinceNbr());
            contractRequestDTO.setIsFixedMoney("0");
            contractRequestDTO.setContractCurrency("01");
            contractRequestDTO.setCustCode(contractRequestDTO.getCustId());
            contractRequestDTO.setDepartId(KiteStringUtils.valueOf(loginInfo.getPostInfos().get(0).getPostId()));
            contractRequestDTO.setDepartName(KiteStringUtils.valueOf(loginInfo.getPostInfos().get(0).getPostName()));
            contractRequestDTO.setStatusCode("305");
            String operNo = (String) ContextUtil.getLoginInfo().getUserInfo().getExtParams().get("account");
            contractRequestDTO.setOperNo(operNo);
            contractRequestDTO.setOperName(loginInfo.getStaffInfo().getStaffName());
            try {
                SOAPEnvelope soap = WebServiceUtil.invoke(WebServiceHelper.replaceCreateContractReq(contractRequestDTO), SpringUtil.getBean(ICuccQueryInfService.class).getUrlByType(infService));
                return WebServiceHelper.dealCreateContractResp(soap,contractRequestDTO.getAccessoryId());
            }
            catch (Exception e) {
                // TODO Auto-generated catch block
//            e.printStackTrace();
                LOGGER.error(e.getMessage());
            }
        }else{
            Map<String, Object> contractInfoMap = infServiceBus.createAndUploadContract(contractRequestDTO);
            List<KitePosAttachmentDTO> attachments = new ArrayList<KitePosAttachmentDTO>();
            List<Map>  ATTACHMENTS = (List) contractInfoMap.get("ATTACHMENTS");
            ATTACHMENTS.stream().forEach (Map-> {
                KitePosAttachmentDTO attachements = new KitePosAttachmentDTO();
                attachements.setName(KiteMapUtils.getString(Map, "ACCESSORY_NAME"));
                attachements.setUrl(KiteMapUtils.getString(Map, "PREVIEW_ADDRESS"));
                attachements.setAccessoryId(KiteMapUtils.getString(Map, "ACCESSORY_ID"));
                attachements.setCatagory("13");
                attachments.add(attachements);
            });
            contractInfoMap.put("ATTACHMENTS",attachments);
            ContractSimpleDTO dto = JsonUtils.parseObject(contractInfoMap.toString(), ContractSimpleDTO.class);
            return dto;
        }

       /* LOGGER.info(KiteMapUtils.getLong(contractInfoMap, "CONTRACT_ID"));
        contractSimpleDTO.setContractNo(KiteMapUtils.getString(contractInfoMap, "CONTRACT_NO"));
        contractSimpleDTO.setContractName(KiteMapUtils.getString(contractInfoMap, "CONTRACT_NAME"));
        LOGGER.info(KiteMapUtils.getLong(contractInfoMap, "CONTRACT_ID"));
        contractSimpleDTO.setContractId(KiteMapUtils.getLong(contractInfoMap, "CONTRACT_ID").toString());*/
        return null;
    }

    @Override
    public DownloadIncludeDataDTO downloadIncludeData(String goodsCode, String categroyCode, String sceneInstId,
                                                      String staffId, String orgId, CuccContextCustDTO custDto) {
        Map<String, Object> param = new HashMap<>();
        //下载不需要合同信息
        IOperateSceneInstService querySceneInstService = SpringUtil.getBean(IOperateSceneInstService.class);
        querySceneInstService.putExtParameter(sceneInstId, "downloadFile", "T");

        IKitePosServiceHandler handler = SpringUtil.getBean(KitePosServiceHandler.class);
        KitePosDTO pos = handler.deal(sceneInstId, staffId, orgId, custDto, true, true, null);
        /*DownloadIncludeDataRequestDTO request = new DownloadIncludeDataRequestDTO();
        BeanUtils.copyProperties(pos, request);*/

        Offer offer = OfferCache.get(pos.getGoods().get(0).getCode());
        List<OfferAttr> attrs = offer.listOfferAttrs().stream().filter((attr) -> "cateId".equals(attr.getFieldName())).collect(Collectors.toList());

        Map<String, String> posMap = new HashMap<>();
        posMap.put("goodsCode", pos.getGoods().get(0).getCode());
        posMap.put("categroyCode", attrs.get(0).getDefaultValue()); //attrs.get(0).getDefaultValue()
        posMap.put("receiveInformation", JSONObject.toJSON(pos).toString());

        // TODO 待塞入真实数据
        /*request.setVersion(1);
        request.setSerialNo("1583314468445");
        request.setSourceMall("1");
        request.setSourceMallName("订单中心");
        request.setSourceOrderId("10000000049463");
        param.put("goodsCode", goodsCode);
        param.put("categroyCode", categroyCode);
        param.put("receiveInformation", );*/
        String rsp = HttpsCallClient.postString(CallClientEnum.DOWNLOAD_CONTRACT, posMap);
        Map<String, String> dataMap = JSON.parseObject(rsp, Map.class);
        String status = KiteMapUtils.getString(dataMap, "status");
        if (!"0".equals(status)) {
            return null;
        }

        String tempData = JsonUtils.parseObject(rsp).getJSONObject("data").getString("tempData");
        String tempName = JsonUtils.parseObject(rsp).getJSONObject("data").getString("tempName");

        DownloadIncludeDataDTO dto = new DownloadIncludeDataDTO();
        dto.setTempData(tempData);
        dto.setTempName(tempName);
        return dto;
    }

    @Override
    public String queryContractType(String cataId) {
        Map<String, String> param = new HashMap<>();
        param.put("info", cataId);
        String rsp = HttpsCallClient.postString(CallClientEnum.QRY_CUSTOMER_CONTRACTTYPE, param);
        Map<String, String> typeMap = JSON.parseObject(rsp, Map.class);
        return Optional.ofNullable(typeMap).map((data) -> data.get("data")).orElse("");
    }

    /**
     * 合同信息-存量合同查询
     */
    @Override
    public PageInfo<CustContractRsp> queryContractInfoByCustId(@KiteNotBlank String custId, String contractNo,
                                                               String contractName, String dataCode, String provinceCode, @KiteNotBlank int pageNum,
                                                               @KiteNotBlank int pageSize,String cateId) {
        PageInfo<CustContractRsp> pageInfo = new PageInfo<CustContractRsp>();

        String code= DcPublicCache.getPCode("20211224001","ZWY");
        if(KiteStringUtils.isNotEmpty(cateId)&&KiteStringUtils.isNotEmpty(cateId)&&KiteStringUtils.contains(code,cateId)){
            List<CustContractRsp> contractInfoList = infServiceBus.listContractInfo(custId, contractNo, contractName,
                dataCode, provinceCode, pageNum, pageSize,cateId);
            pageInfo.setList(contractInfoList);
        }else{
            Map<String, Object> contractInfoMap = infServiceBus.listContractInfos(custId, contractNo, contractName,
                dataCode, provinceCode, pageNum, pageSize,null);
            List<CustContractRsp> list = InfServiceBus.dealContractResp((List<Map<String, Object>>) contractInfoMap.get("list"));
            int total=Integer.parseInt(KiteMapUtils.getString(contractInfoMap, "totalCount"));
            pageInfo.setList(list);
            pageInfo.setTotal(total);
        }
        return pageInfo;
    }

}
